package com.campusflea;

import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.campusflea.DateBase.Purchase;
import com.campusflea.DateBase.ShopInfo;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import cn.bmob.v3.Bmob;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.SaveListener;

public class GoodsDetailsActivity extends AppCompatActivity implements ViewPager.OnPageChangeListener {
    private ViewPager mViewPager = null;
    private LinearLayout mViewGroup = null;
    //private int[] mImageIds = {R.mipmap.c1,R.mipmap.c2,R.mipmap.c3,R.mipmap.c4,R.mipmap.c5,R.mipmap.c6,R.mipmap.c7,R.mipmap.c8};
    private ImageView[] mImageViews = null;
    private ImageView[] mTips = null;
    private ShopInfo shopInfo_shop;
    private ShopInfo shopInfo_sale;
    private TextView goodsTitle,goodsDetails,goodsPrice,goodsPhone;
    private RelativeLayout tips_grounp;
    private ImageView imageView;
    private String url,phone;
    private Bitmap bitmap=null;
    private Button btn_buy;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_goods_details);
//        tips_grounp = (RelativeLayout)findViewById(R.id.tips_grounp);
//        tips_grounp.setVisibility(View.GONE);//现在只有一张图片，故将下方的小点隐藏
////*
/// 解决图片不能显示问题，即networkonmainThread异常
/// */
        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
                .detectDiskReads().detectDiskWrites().detectNetwork()
                .penaltyLog().build());
        StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
                .detectLeakedSqlLiteObjects().detectLeakedClosableObjects()
                .penaltyLog().penaltyDeath().build());

        goodsTitle = (TextView)findViewById(R.id.goodsTitle);
        goodsDetails = (TextView)findViewById(R.id.goodsDetails);
        goodsPrice = (TextView)findViewById(R.id.goodsPrice);
        imageView = (ImageView)findViewById(R.id.imageshop) ;
        goodsPhone=(TextView)findViewById(R.id.goodsPhone);
        btn_buy= (Button) findViewById(R.id.buy);
        Bmob.initialize(this,"36b62198745ed1900e5f1e8d55eb660d");
        //Intent intent=getIntent();
        //String a=intent.getStringExtra("js");
        shopInfo_shop= (ShopInfo) getIntent().getSerializableExtra("shop");
        Intent intent=getIntent();
        phone=intent.getExtras().getString("phone");
        shopInfo_sale= (ShopInfo) getIntent().getSerializableExtra("sale");
        Intent intent_sale=getIntent();
        if(shopInfo_shop.getPublisher().equals(phone)){
            //设置购买按钮的颜色灰色，取消点击事件
            btn_buy.setBackgroundResource(R.color.gray);
        }
        if(shopInfo_shop!=null){
//            Bitmap bitmap=intent.getParcelableExtra("pic");
//            imageView.setImageBitmap(bitmap);
//            new Thread(networkTask).start();
            url=shopInfo_shop.getBmobFile().getFileUrl();
            Bitmap bitmap1=getHttpBitmap(url);
             imageView.setImageBitmap(bitmap1);
            goodsTitle.setText(shopInfo_shop.getShop_name());
            goodsDetails.setText(shopInfo_shop.getShop_disc());
            goodsPrice.setText("￥"+shopInfo_shop.getShop_price());
            goodsPhone.setText(shopInfo_shop.getPublisher());
        }else if (shopInfo_sale!=null){
            String url=shopInfo_sale.getBmobFile().getFileUrl();
            Bitmap bitmap=getHttpBitmap(url);
            imageView.setImageBitmap(bitmap);
            goodsTitle.setText(shopInfo_sale.getShop_name());
            goodsDetails.setText(shopInfo_sale.getShop_disc());
            goodsPrice.setText("￥"+shopInfo_sale.getShop_price());
            goodsPhone.setText(shopInfo_sale.getPublisher());
        }

        mViewGroup = (LinearLayout) findViewById(R.id.viewGroup);
        mViewPager = (ViewPager) findViewById(R.id.viewPager);
        btn_buy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(shopInfo_shop.getPublisher().equals(phone)){
                    Toast.makeText(GoodsDetailsActivity.this,"不能购买",Toast.LENGTH_LONG).show();

                }
                else {
                    Purchase purchase = new Purchase();
                    purchase.setShopId(shopInfo_shop.getObjectId());
                    purchase.setPurchaser(phone);
                    purchase.save(new SaveListener<String>() {
                        @Override
                        public void done(String s, BmobException e) {
                            Toast.makeText(GoodsDetailsActivity.this,"购买成功",Toast.LENGTH_LONG).show();
                        }
                    });
                }
            }
        });
       /* mTips = new ImageView[mImageIds.length];
        //动态创建小点并加到布局中
        for(int i = 0; i < mTips.length; i++)
        {
            ImageView iv = new ImageView(this);
            iv.setLayoutParams(new ViewPager.LayoutParams());
            mTips[i] = iv;

            if(i == 0)
            {
                iv.setBackgroundResource(R.mipmap.xuanzhong);
            }else
            {
                iv.setBackgroundResource(R.mipmap.noxuanzhong);
            }
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewPager.LayoutParams.WRAP_CONTENT,
                    ViewPager.LayoutParams.WRAP_CONTENT);
            //   lp.leftMargin = 5;
            //  lp.rightMargin = 5;
            mViewGroup.addView(iv,lp);
        }*/
//        mImageViews = new ImageView[1];
//        for(int i = 0; i < mImageViews.length; i++) {
//            ImageView iv = new ImageView(this);
//            mImageViews[i] = iv;
//            int reqWidth = getWindowManager().getDefaultDisplay().getWidth();
//            int reqHeight = getWindowManager().getDefaultDisplay().getHeight();
//            //iv.setImageBitmap(bitmap);//设置图片
//
//            //iv.setImageBitmap(decodeSampledBitmapFromResource(getResources(), mImageIds[i], reqWidth, reqHeight));
//
//        }
//        mViewPager.setAdapter(new MyPagerAdapter());
//        mViewPager.setOnPageChangeListener(this);
    }
//    Handler handler = new Handler() {
//        @Override
//        public void handleMessage(Message msg) {
//            super.handleMessage(msg);
//            Bundle data = msg.getData();
//            String url1 = data.getString("value");
//
//            // TODO
//            // UI界面的更新等相关操作
//
//            URL myUrl;
//
//            try {
//                myUrl=new URL(url1);
//                HttpURLConnection conn=(HttpURLConnection)myUrl.openConnection();
//                conn.setConnectTimeout(5000);
//                conn.connect();
//                InputStream is=conn.getInputStream();
//                bitmap=BitmapFactory.decodeStream(is);
//                is.close();
//            } catch (MalformedURLException e) {
//                // TODO Auto-generated catch block
//                e.printStackTrace();
//            } catch (IOException e) {
//                // TODO Auto-generated catch block
//                e.printStackTrace();
//            }
//            //返回圆形bitmap
//        }
//    };
//    Runnable networkTask = new Runnable() {
//
//        @Override
//        public void run() {
//            Message msg = new Message();
//            Bundle data = new Bundle();
//            data.putString("value", url);
//            msg.setData(data);
//            handler.sendMessage(msg);
//
//        }
//    };
    /**
     * 根据URL获取Bitmap
     * */
    public Bitmap getHttpBitmap(String url){
        Bitmap bitmap=null;
        URL myUrl;

        try {
            myUrl=new URL(url);
            HttpURLConnection conn=(HttpURLConnection)myUrl.openConnection();
            conn.setConnectTimeout(5000);
            conn.connect();
            InputStream is=conn.getInputStream();
            bitmap=BitmapFactory.decodeStream(is);
            is.close();
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //返回圆形bitmap
        return bitmap;
    }
    class MyPagerAdapter extends PagerAdapter
    {
        @Override
        public int getCount()
        {
            return mImageViews.length;
        }
        @Override
        public boolean isViewFromObject(View arg0, Object arg1)
        {
            return arg0 == arg1;
        }
        @Override
        public Object instantiateItem(ViewGroup container, int position)
        {
            try
            {
                container.addView(mImageViews[position]);
            } catch (Exception e)
            {
            }
            return mImageViews[position];
        }
        @Override
        public void destroyItem(ViewGroup container, int position, Object object)
        {
        }
    }

    public void onPageSelected(int arg0)
    {
        for(int i = 0; i < mTips.length; i++)
        {
            if(arg0 == i)
            {
                mTips[i].setBackgroundResource(R.mipmap.xuanzhong);
            }else
            {
                mTips[i].setBackgroundResource(R.mipmap.noxuanzhong);
            }
        }
    }

    public void onPageScrollStateChanged(int arg0)
    {
    }

    public void onPageScrolled(int arg0, float arg1, int arg2)
    {
    }

    private static Bitmap decodeSampledBitmapFromResource(Resources res, int resId, int reqWidth, int reqHeight)
    {
        BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inJustDecodeBounds = true;
        BitmapFactory.decodeResource(res, resId);
        int inSampleSize = cacluateInSampledSize(opts, reqWidth, reqHeight);
        opts.inSampleSize = inSampleSize;
        opts.inJustDecodeBounds = false;
        return BitmapFactory.decodeResource(res,resId,opts);
    }

    private static int cacluateInSampledSize(BitmapFactory.Options opts,int width,int height)
    {
        if(opts == null)
        {
            return 1;
        }
        int inSampleSize = 1;
        int realWidth = opts.outWidth;
        int realHeight = opts.outHeight;

        if(realWidth > width || realHeight > height)
        {
            int heightRatio = realHeight/height;
            int widthRatio = realWidth/width;

            inSampleSize = (widthRatio > heightRatio) ? heightRatio : widthRatio;
        }
        return inSampleSize;
    }
}
